import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {FetchService} from '../../../core/net/fetch.service';
import {NzMessageService} from 'ng-zorro-antd';
import {Router} from "@angular/router";
import {isToday, format} from 'date-fns';

@Component({
  selector: 'app-work-change',
  templateUrl: './work-change.component.html',
  styleUrls: ['./work-change.component.scss']
})
export class WorkChangeComponent implements OnInit {
  searchForm: FormGroup;
  manageId = JSON.parse(localStorage.userInfo).manageId;
  tableData;
  total: number;
  pageNum = 1;
  pageSize = 20;
  loading = true;
  form: FormGroup;
  modalTitle: string = '';
  modalShow: boolean = false;
  nzBodyStyle: any = {
    padding: '16px 20px 0'
  };
  detailList = [];
  peopleOption;
  selectedId;

  constructor(private fb: FormBuilder,
              private fetchService: FetchService,
              private router: Router,
              private message: NzMessageService) {
    this.searchForm = this.fb.group({
      keyword: [null],
      rangePickerTime: [[]],
      toStaff: [null],
      fromStaff: [null]
    });

    this.form = this.fb.group({
      id: [null],
      toStaff: [null],
      changeDate: [null],
      content: [null],
      advice: [null]
    });
  }

  ngOnInit(): void {
    this.getPeopleOption();
    this.queryInfo();
  }

  queryInfo(reset: boolean = false): void {
    if (reset) {
      this.pageNum = 1;
    }
    const stDate = this.searchForm.value.rangePickerTime[0] ? format(this.searchForm.value.rangePickerTime[0], 'YYYY-MM-DD') : '';
    const edDate = this.searchForm.value.rangePickerTime[1] ? format(this.searchForm.value.rangePickerTime[1], 'YYYY-MM-DD') : '';
    const param = {
      orderByField: 'changeDate',
      orderBy: 'desc',
      manageId: JSON.parse(localStorage.userInfo).manageId,
      pageNum: this.pageNum,
      pageSize: this.pageSize,
      keyword: this.searchForm.value.keyword,
      toStaff: this.searchForm.value.toStaff,
      fromStaff: this.searchForm.value.fromStaff,
      stDate: stDate,
      edDate: edDate
    };
    this.fetchService.post<any>('schedule/wrsWorkChange/list', param).subscribe(res => {
      this.loading = false;
      if (res) {
        this.total = res['total'];
        this.tableData = res['list'];
        if (this.tableData.length > 0) {
          this.getDetail(this.tableData[0].date);
        }
      }
    });
  }

  getDetail(date): void {
    this.fetchService.post<any>('schedule/wrsWorkChange/queryByChageDate', {changeDate: date}).subscribe(res => {
      this.detailList = res;
    });
  }

  getPeopleOption() {
    this.fetchService.post<any>('sys/sysApiInfo/queryApiData', {manageId: this.manageId, apicode: '15'})
      .subscribe(res => {
        this.peopleOption = res;
        this.peopleOption.unshift({name: '请选择', id: ''});
      });
  }

  openEditModal(item?): void {
    this.modalTitle = '编辑交接班记录';
    this.modalShow = true;
    this.form.patchValue(item);
  }

  onConfirm() {
    if (!this.form.valid) {
      this.message.warning('信息填写有误');
      return;
    }
    const param: any = {
      toStaff: this.form.value.toStaff,
      changeDate: format(this.form.value.changeDate, 'YYYY-MM-DD HH:mm:ss'),
      advice: this.form.value.advice,
      content: this.form.value.content
    };
    if (this.form.value.id) {
      param.id = this.form.value.id;
      this.fetchService.post('schedule/wrsWorkChange/edit', param).subscribe(res => {
        this.message.success('操作成功！');
        this.modalShow = false;
        this.queryInfo();
      });
    } else {
      this.fetchService.post('schedule/wrsWorkChange/add', param).subscribe(res => {
        this.message.success('操作成功！');
        this.modalShow = false;
        this.queryInfo();
      });
    }
  }

  rowSelect(data) {
    this.selectedId = data.date;
    this.getDetail(data.date);
  }

  onAdd(): void {
    this.modalTitle = '新增交接班记录';
    this.modalShow = true;
    this.getNextStaff();

  }

  onCancel() {
    this.modalShow = false;
  }

  getNextStaff(): void {
    this.fetchService.post<any>('schedule/wrsOnDuty/queryNowStaff', {}).subscribe(res => {
      this.form.reset();
      this.form.patchValue({changeDate: new Date()});
      this.form.patchValue({toStaff: res.member});
    });
  }

  exportDocx() {
    let params;
    if (!this.searchForm.value.rangePickerTime[0]) {
      params = {
        stDate: this.tableData[0].date,
        edDate: this.tableData[0].date,
        manageId: JSON.parse(localStorage.userInfo).manageId
      };
    } else {
      params = {
        stDate: format(this.searchForm.value.rangePickerTime[0], 'YYYY-MM-DD'),
        edDate: format(this.searchForm.value.rangePickerTime[1], 'YYYY-MM-DD'),
        manageId: JSON.parse(localStorage.userInfo).manageId
      };
    }
    this.fetchService.export(`comm/word/exportWord`, {
      wordMapper: 'WordMapper-WrsWorkChangeWord',
      queryParams: JSON.stringify(params),
      targetFileName: '交接班记录.docx'
    }).subscribe(data => {
      const fileBlob = new Blob([data], { type: 'charset=utf-8' });
      const link = document.createElement('a');
      link.id = 'workChangeDownloadId';
      document.body.appendChild(link);
      link.style.display = 'none';
      link.download = '交接班记录.docx';
      link.href = URL.createObjectURL(fileBlob);
      link.click();
      const tempA = document.getElementById('workChangeDownloadId');
      if (tempA) {
        tempA.parentNode.removeChild(tempA);
      }
    });
  }
}
